package com.doudanhua.basecode.jackson.time;

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Date;

import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE;
import static java.time.format.DateTimeFormatter.ISO_LOCAL_TIME;

/**
 * @Author zhangqian
 * @Description TODO
 * @Date 2022/11/4 17:14
 */
public abstract class DateTimeConverter {
    protected static final DateTimeFormatter dateTimeFormatter;
    static final String MIN_DATE_RESULT = "0001-01-01T00:00:00+00:00";

    static {
        dateTimeFormatter = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .append(ISO_LOCAL_DATE)
                .optionalStart()
                .appendLiteral(' ')        // ' ' made optional
                .optionalEnd()
                .optionalStart()
                .appendLiteral('T')        // 'T' made optional
                .optionalEnd()
                .optionalStart()
                .append(ISO_LOCAL_TIME)    // time made optional
                .optionalEnd()
                .optionalStart()           // zone and offset made optional
                .appendOffsetId()
                .optionalEnd()
                .optionalStart()
                //为了兼容时区不带:这种格式
                .appendOffset("+HHMM", "Z")
                .optionalEnd()
                .optionalStart()
                .appendLiteral('[')
                .parseCaseSensitive()
                .appendZoneRegionId()
                .appendLiteral(']')
                .optionalEnd()
                .toFormatter();
    }


    public Date parseDate(String value) {
        return Date.from(parse(value).toInstant());
    }

    public LocalDateTime parseLocalDateTime(String value) {
        return parse(value).toLocalDateTime();
    }

    public ZonedDateTime parseZonedDateTime(String value) {
        return parse(value);
    }

    public abstract String format(Date value);

    public abstract String format(LocalDateTime value);

    public abstract String format(ZonedDateTime value);

    protected abstract ZonedDateTime parse(String value);
}

